package com.aismy.admin.service.impl;

import com.aismy.admin.entity.EvalRecord;
import com.aismy.admin.entity.EvalScale;
import com.aismy.admin.entity.Question;
import com.aismy.admin.entity.SysUser;
import com.aismy.admin.exception.BusinessException;
import com.aismy.admin.mapper.EvalRecordMapper;
import com.aismy.admin.mapper.EvalScaleMapper;
import com.aismy.admin.service.EvalRecordService;
import com.aismy.admin.service.EvalScaleService;
import com.aismy.admin.service.UserService;
import com.aismy.admin.utils.AiUtils;
import com.aismy.admin.utils.Json;
import com.aismy.admin.vo.AiResult;
import com.aismy.admin.vo.EvalRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class EvalRecordServiceImpl extends ServiceImpl<EvalRecordMapper, EvalRecord> implements EvalRecordService {
    private final UserService userService;
    private final EvalScaleMapper scaleMapper;
    private final AiUtils aiUtils;

    @Override
    public Page<EvalRecordVo> getRecordPage(Integer page, Integer size, String query) {
        Page<EvalRecord> paged = this.page(
                new Page<>(page, size),
                new LambdaQueryWrapper<EvalRecord>()
                        .like(StringUtils.isNotBlank(query), EvalRecord::getUserId, query)
                        .orderByDesc(EvalRecord::getCreatedAt)
        );
        Page<EvalRecordVo> pageVo = new Page<>(paged.getCurrent(), paged.getSize(), paged.getTotal());
        //获取用户名
        Set<Long> userIds = paged.getRecords().stream().map(EvalRecord::getUserId).collect(Collectors.toSet());
        Set<Long> scaleIds = paged.getRecords().stream().map(EvalRecord::getScaleId).collect(Collectors.toSet());
        List<SysUser> users = userService.list(new LambdaQueryWrapper<SysUser>()
                .in(SysUser::getId, userIds));
        // 转成map
        Map<Long, SysUser> userMap = users.stream().collect(Collectors.toMap(SysUser::getId, user -> user));

        List<EvalScale> scales = scaleMapper.selectList(new LambdaQueryWrapper<EvalScale>()
                .in(EvalScale::getId, scaleIds));
        Map<Long, EvalScale> scaleMap = scales.stream().collect(Collectors.toMap(EvalScale::getId, scale -> scale));
        List<EvalRecordVo> voList = new ArrayList<>();
        for (EvalRecord record : paged.getRecords()) {
            EvalRecordVo vo = new EvalRecordVo();
            vo.setEvaluation(record.getEvaluation());
            vo.setLevel(record.getLevel());
            vo.setTotalScore(record.getTotalScore());
            vo.setUserName(userMap.get(record.getUserId()).getUsername());
            vo.setScaleName(scaleMap.get(record.getScaleId()).getName());
            vo.setCreatedAt(record.getCreatedAt());
            vo.setId(record.getId());
            voList.add(vo);
        }
        pageVo.setRecords(voList);
        return pageVo;
    }

    @Override
    public AiResult generateAiResult(Long id) {
        EvalRecord record = getById(id);
        String submitData = record.getSubmitData();
        Optional<String> result = aiUtils.sendMessage(buildMessage(submitData));
        if (result.isEmpty()) {
            throw new BusinessException("ai fail");
        }
        String json = result.get().substring(result.get().indexOf("{"), result.get().lastIndexOf("}") + 1);
        return Json.parse(json, AiResult.class);
    }

    public String buildMessage(String submitData) {
        StringBuilder message = new StringBuilder();
        message.append("以下留守儿童心理测评结果：")
                .append("\n")
                .append("测评结果：").append(submitData)
                .append("\n")
                .append("请你根据结果进行分析，给出分析结果和意见，回答的结果格按照json格式给我，格式如下：")
                .append("\n")
                .append("{result:[],comments:[]}");
        return message.toString();
    }
}